package com.yicong.ants.manager;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;

import com.alipay.sdk.app.PayTask;
import com.cchao.simplelib.LibCore;
import com.cchao.simplelib.core.Router;
import com.cchao.simplelib.core.RxHelper;
import com.cchao.simplelib.core.UiHelper;
import com.cchao.simplelib.ui.activity.BaseStatefulActivity;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.yicong.ants.Constants;
import com.yicong.ants.bean.AuthResultBean;
import com.yicong.ants.bean.PayOrderBean;
import com.yicong.ants.bean.PayResultBean;
import com.yicong.ants.bean.order.WxPay;
import com.yicong.ants.manager.business.SignHelper;
import com.yicong.ants.manager.http.RetrofitHelper;
import com.yicong.ants.mvp.model.listener.OnCallBackModel;
import com.yicong.ants.utils.JsonUtils;
import com.yicong.ants.utils.L;
import com.yicong.ants.utils.StringUtils;
import com.yicong.ants.wxapi.WXPayEntryActivity;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;

/**
 * @author cchao
 * @version 2019-09-27.
 */
public class PayManager {

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;
    // 用于支付结果的跳转
    public static String CUR_PAY_CATEGORY = "ticket";
    private static IWXAPI mWxApi;

    public static void registerWxApi() {
        if (mWxApi == null) {
            mWxApi = WXAPIFactory.createWXAPI(LibCore.getContext(), Constants.WeChatId);
            mWxApi.registerApp(Constants.WeChatId);
        }

        SignHelper.sa2 = "_K";
    }

    /**
     * 请求api 获取加签后的信息，再调用支付宝
     */
    public static void getAliPayOrder(Map<String, String> params, final OnCallBackModel callBackModel) {
        L.e("订单参数数据返回---->", params.toString());

        HttpManager.postHttp(Constants.PAY_ORDERS, params, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                callBackModel.onDataError();
            }

            @Override
            public void onResponse(String response, int id) {
                if (StringUtils.isJSONType(response)) {
                    L.e("订单加签后数据返回---->", response);
                    PayOrderBean bean = JsonUtils.fromJson(response, PayOrderBean.class);
                    if (null == bean) {
                        callBackModel.onDataError();
                        return;
                    }
                    if (bean.getCode().equals(Constants.DATA_SUCCESS)) {
                        callBackModel.onSuccess(bean.getData());
                    } else {
                        callBackModel.onFailure(bean.getMsg());
                    }
                } else {
                    callBackModel.onDataError();
                }
            }
        });
    }

    public static void payByWeChat(BaseStatefulActivity context, Map<String, String> bean) {
        registerWxApi();
        PayManager.getWeChatPayOrder(context, bean, (OnCallBackModel<PayReq>) datas -> {
            mWxApi.sendReq(datas);
        });
    }

    public static void payByAli(BaseStatefulActivity activity, Map<String, String> map) {
        activity.showProgress();
        activity.addSubscribe(RetrofitHelper.getApis().submitAuthAli(map)
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .subscribe(respBean -> {
                    activity.hideProgress();
                    if (respBean.isCodeFail()) {
                        activity.showToast(respBean.getMsg());
                        return;
                    }

                    PayTask alipay = new PayTask(activity);
                    Map<String, String> result = alipay.payV2(respBean.getData(), true);
                    PayManager.waitForAliPay(result, new OnCallBackModel<Boolean>() {
                        @Override
                        public void onSuccess(Boolean datas) {
                            Router.turnTo(activity, WXPayEntryActivity.class)
                                    .putExtra(Constants.Extra.Code, datas ? 0 : 1)
                                    .start();
                        }

                        @Override
                        public void onFailure(String msg) {
                            UiHelper.showToast(msg);
                        }
                    });
                }, RxHelper.getHideProgressConsumer(activity)));
    }

    public static void getWeChatPayOrder(BaseStatefulActivity activity, Map<String, String> params, final OnCallBackModel callBackModel) {
        activity.showProgress();
        activity.addSubscribe(RetrofitHelper.getApis().submitAuthWx(params)
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .subscribe(respBean -> {
                    activity.hideProgress();

                    PayReq req = new PayReq();
                    WxPay wxPay = respBean;
                    req.appId = wxPay.getAppid();
                    req.partnerId = wxPay.getPartnerid();
                    req.prepayId = wxPay.getPrepayid();
                    req.nonceStr = wxPay.getNoncestr();
                    req.timeStamp = wxPay.getTimestamp();
                    req.packageValue = wxPay.getPackageX();
                    req.sign = wxPay.getSign();
                    req.extData = "app data";
                    // Toast.makeText(PayActivity.this, "正常调起支付", Toast.LENGTH_SHORT).show();
                    // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
                    callBackModel.onSuccess(req);
                }, RxHelper.getHideProgressConsumer(activity)));
    }

    public static void getAliPayOrder(String amount, String ordersn, String subject, final OnCallBackModel callBackModel) {
        Map<String, String> params = new HashMap<>(5);
        params.put("amount", amount);
        params.put("type", "alipay");
        params.put("ordersn", ordersn);
        params.put("subject", subject);
        params.put("method", "app");
        HttpManager.postHttp(Constants.PAY_OF_ORDER, params, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                callBackModel.onNetError();
            }

            @Override
            public void onResponse(String response, int id) {
                if (StringUtils.isJSONType(response)) {
                    L.e("订单加签后数据返回---->", response);
                    PayOrderBean bean = JsonUtils.fromJson(response, PayOrderBean.class);
                    if (null == bean) {
                        callBackModel.onDataError();
                        return;
                    }
                    if (bean.getCode().equals(Constants.DATA_SUCCESS)) {
                        callBackModel.onSuccess(bean.getData());
                    } else {
                        callBackModel.onFailure(bean.getMsg());
                    }
                } else {
                    callBackModel.onDataError();
                }
            }
        });
    }

    public static void waitForAliPay(Map<String, String> result, OnCallBackModel callBackModel) {
        initAliPayData(result, callBackModel);
    }

    /**
     * 处理阿里支付的数据
     *
     * @param result
     * @param callBackModel
     */
    public static void initAliPayData(Map<String, String> result, final OnCallBackModel callBackModel) {
        Handler handler = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case SDK_PAY_FLAG: {
                        @SuppressWarnings("unchecked")
                        PayResultBean payResult = new PayResultBean((Map<String, String>) msg.obj);
                        /**
                         对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                         */
                        //  String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                        String resultStatus = payResult.getResultStatus();
                        // 判断resultStatus 为9000则代表支付成功
                        if (TextUtils.equals(resultStatus, "9000")) {
                            // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                            // 支付成功
                            callBackModel.onSuccess(true);
                        } else {
                            // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                            // 支付失败
                            callBackModel.onSuccess(false);
                        }
                        break;
                    }
                    case SDK_AUTH_FLAG: {
                        @SuppressWarnings("unchecked")
                        AuthResultBean authResult = new AuthResultBean((Map<String, String>) msg.obj, true);
                        String resultStatus = authResult.getResultStatus();

                        // 判断resultStatus 为“9000”且result_code
                        // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                        if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                            // 获取alipay_open_id，调支付时作为参数extern_token 的value
                            // 传入，则支付账户为该授权账户
                            callBackModel.onFailure("授权成功\n" + String.format("authCode:%s", authResult.getAuthCode()));
                        } else {
                            // 其他状态值则为授权失败
                            callBackModel.onFailure("授权失败" + String.format("authCode:%s", authResult.getAuthCode()));
                        }
                        break;
                    }
                }
            }
        };
        Message msg = new Message();
        msg.what = SDK_PAY_FLAG;
        msg.obj = result;
        handler.sendMessage(msg);
    }

    public static void getWeChatOrder(String amount, String ordersn, String subject, final OnCallBackModel callBackModel) {
        Map<String, String> params = new HashMap<>(5);
        params.put("amount", amount);
        params.put("type", "wechat");
        params.put("ordersn", ordersn);
        params.put("subject", subject);
        params.put("method", "app");
        L.e("getWeChatOrder--------A", params.toString());
        HttpManager.postHttp(Constants.PAY_OF_ORDER, params, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                L.e("getWeChatOrder-----onError", e.getMessage());
                callBackModel.onNetError();
            }

            @Override
            public void onResponse(String response, int id) {
                initWeChatData(response, callBackModel);
            }
        });
    }

    /**
     * 处理微信返回的数据
     */
    public static void initWeChatData(String response, OnCallBackModel callBackModel) {
        if (!StringUtils.isJSONType(response)) {
            callBackModel.onDataError();
            return;
        }
        JSONObject json = null;
        try {
            json = new JSONObject(response);
            L.e("initWeChatData---->", json.toString());

            if (!json.has("retcode")) {
                L.e("getWeChatOrder--------json", json.toString());
                PayReq req = new PayReq();
                //req.appId = "wxf8b4f85f3a794e77";  // 测试用appId
                try {
                    req.appId = json.getString("appid");
                    req.partnerId = json.getString("partnerid");
                    req.prepayId = json.getString("prepayid");
                    req.nonceStr = json.getString("noncestr");
                    req.timeStamp = json.getString("timestamp");
                    req.packageValue = json.getString("package");
                    req.sign = json.getString("sign");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                req.extData = "app data"; // optional
                // Toast.makeText(PayActivity.this, "正常调起支付", Toast.LENGTH_SHORT).show();
                // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
                callBackModel.onSuccess(req);
            } else {
                callBackModel.onFailure(json.getString("retmsg"));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
